{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qFdPvlXBOdUN"
      },
      "source": [
        "# Pruning in Keras example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/model_optimization/guide/pruning/pruning_with_keras\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/pruning/pruning_with_keras.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/pruning/pruning_with_keras.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/model-optimization/tensorflow_model_optimization/g3doc/guide/pruning/pruning_with_keras.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Bjmi3qZeu_xk"
      },
      "source": [
        "## Overview\n",
        "\n",
        "Welcome to an end-to-end example for magnitude-based *weight pruning*.\n",
        "\n",
        "### Other pages\n",
        "For an introduction to what pruning is and to determine if you should use it (including what's supported), see the [overview page](https://www.tensorflow.org/model_optimization/guide/pruning).\n",
        "\n",
        "To quickly find the APIs you need for your use case (beyond fully pruning a model with 80% sparsity), see the\n",
        "[comprehensive guide](https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide.md).\n",
        "\n",
        "### Summary\n",
        "\n",
        "In this tutorial, you will:\n",
        "\n",
        "1.   Train a `keras` model for MNIST from scratch.\n",
        "2.   Fine tune the model by applying the pruning API and see the accuracy.\n",
        "3.   Create 3x smaller TF and TFLite models from pruning.\n",
        "4.   Create a 10x smaller TFLite model from combining pruning and post-training quantization.\n",
        "5.   See the persistence of accuracy from TF to TFLite."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yEAZYXvZU_XG"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zN4yVFK5-0Bf"
      },
      "outputs": [],
      "source": [
        "! pip install -q tensorflow-model-optimization"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yJwIonXEVJo6"
      },
      "outputs": [],
      "source": [
        "import tempfile\n",
        "import os\n",
        "\n",
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "\n",
        "from tensorflow_model_optimization.python.core.keras.compat import keras\n",
        "\n",
        "%load_ext tensorboard"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "psViY5PRDurp"
      },
      "source": [
        "## Train a model for MNIST without pruning"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pbY-KGMPvbW9"
      },
      "outputs": [],
      "source": [
        "# Load MNIST dataset\n",
        "(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\n",
        "\n",
        "# Normalize the input image so that each pixel value is between 0 and 1.\n",
        "train_images = train_images / 255.0\n",
        "test_images = test_images / 255.0\n",
        "\n",
        "# Define the model architecture.\n",
        "model = keras.Sequential([\n",
        "  keras.layers.InputLayer(input_shape=(28, 28)),\n",
        "  keras.layers.Reshape(target_shape=(28, 28, 1)),\n",
        "  keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation='relu'),\n",
        "  keras.layers.MaxPooling2D(pool_size=(2, 2)),\n",
        "  keras.layers.Flatten(),\n",
        "  keras.layers.Dense(10)\n",
        "])\n",
        "\n",
        "# Train the digit classification model\n",
        "model.compile(optimizer='adam',\n",
        "              loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "model.fit(\n",
        "  train_images,\n",
        "  train_labels,\n",
        "  epochs=4,\n",
        "  validation_split=0.1,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G1qKfXNqo9hk"
      },
      "source": [
        "Evaluate baseline test accuracy and save the model for later usage."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RyIKnbVZafIH"
      },
      "outputs": [],
      "source": [
        "_, baseline_model_accuracy = model.evaluate(\n",
        "    test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy)\n",
        "\n",
        "_, keras_file = tempfile.mkstemp('.h5')\n",
        "keras.models.save_model(model, keras_file, include_optimizer=False)\n",
        "print('Saved baseline model to:', keras_file)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "K8747K9OE72P"
      },
      "source": [
        "## Fine-tune pre-trained model with pruning\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F19k7ExXF_h2"
      },
      "source": [
        "### Define the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JsZROpNYMWQ0"
      },
      "source": [
        "You will apply pruning to the whole model and see this in the model summary.\n",
        "\n",
        "In this example, you start the model with 50% sparsity (50% zeros in weights)\n",
        "and end with 80% sparsity.\n",
        "\n",
        "In the [comprehensive guide](https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide.md), you can see how to prune some layers for model accuracy improvements."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oq6blGjgFDCW"
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_optimization as tfmot\n",
        "\n",
        "prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude\n",
        "\n",
        "# Compute end step to finish pruning after 2 epochs.\n",
        "batch_size = 128\n",
        "epochs = 2\n",
        "validation_split = 0.1 # 10% of training set will be used for validation set. \n",
        "\n",
        "num_images = train_images.shape[0] * (1 - validation_split)\n",
        "end_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs\n",
        "\n",
        "# Define model for pruning.\n",
        "pruning_params = {\n",
        "      'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,\n",
        "                                                               final_sparsity=0.80,\n",
        "                                                               begin_step=0,\n",
        "                                                               end_step=end_step)\n",
        "}\n",
        "\n",
        "model_for_pruning = prune_low_magnitude(model, **pruning_params)\n",
        "\n",
        "# `prune_low_magnitude` requires a recompile.\n",
        "model_for_pruning.compile(optimizer='adam',\n",
        "              loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "model_for_pruning.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uDr2ijwpGCI-"
      },
      "source": [
        "### Train and evaluate the model against baseline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XUBEn94hXYB1"
      },
      "source": [
        "Fine tune with pruning for two epochs.\n",
        "\n",
        "`tfmot.sparsity.keras.UpdatePruningStep` is required during training, and `tfmot.sparsity.keras.PruningSummaries` provides logs for tracking progress and debugging."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_PHDGJryE31X"
      },
      "outputs": [],
      "source": [
        "logdir = tempfile.mkdtemp()\n",
        "\n",
        "callbacks = [\n",
        "  tfmot.sparsity.keras.UpdatePruningStep(),\n",
        "  tfmot.sparsity.keras.PruningSummaries(log_dir=logdir),\n",
        "]\n",
        "  \n",
        "model_for_pruning.fit(train_images, train_labels,\n",
        "                  batch_size=batch_size, epochs=epochs, validation_split=validation_split,\n",
        "                  callbacks=callbacks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-byC2lYlMkfN"
      },
      "source": [
        "For this example, there is minimal loss in test accuracy after pruning, compared to the baseline."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6bMFTKSSHyyZ"
      },
      "outputs": [],
      "source": [
        "_, model_for_pruning_accuracy = model_for_pruning.evaluate(\n",
        "   test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy) \n",
        "print('Pruned test accuracy:', model_for_pruning_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zQFiZsqqc0vS"
      },
      "source": [
        "The logs show the progression of sparsity on a per-layer basis."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LdLm4hVYc1wx"
      },
      "outputs": [],
      "source": [
        "#docs_infra: no_execute\n",
        "%tensorboard --logdir={logdir}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d1UFCxxSIIf5"
      },
      "source": [
        "For non-Colab users, you can see [the results of a previous run](https://tensorboard.dev/experiment/sRQnrycaTMWQOaswXzClYA/#scalars\u0026_smoothingWeight=0) of this code block on [TensorBoard.dev](https://tensorboard.dev/)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2IepmUPSITn6"
      },
      "source": [
        "## Create 3x smaller models from pruning"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1FgNP4rbOLH8"
      },
      "source": [
        "Both `tfmot.sparsity.keras.strip_pruning` and applying a standard compression algorithm (e.g. via gzip) are necessary to see the compression\n",
        "benefits of pruning.\n",
        "\n",
        "*   `strip_pruning` is necessary since it removes every tf.Variable that pruning only needs during training, which would otherwise add to model size during inference\n",
        "*   Applying a standard compression algorithm is necessary since the serialized weight matrices are the same size as they were before pruning. However, pruning makes most of the weights zeros, which is\n",
        "added redundancy that algorithms can utilize to further compress the model.\n",
        "\n",
        "First, create a compressible model for TensorFlow."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "w7fztWsAOHTz"
      },
      "outputs": [],
      "source": [
        "model_for_export = tfmot.sparsity.keras.strip_pruning(model_for_pruning)\n",
        "\n",
        "_, pruned_keras_file = tempfile.mkstemp('.h5')\n",
        "keras.models.save_model(model_for_export, pruned_keras_file, include_optimizer=False)\n",
        "print('Saved pruned Keras model to:', pruned_keras_file)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "X4_bixlrtTbF"
      },
      "source": [
        "Then, create a compressible model for TFLite."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "uIKxSSHmrJSa"
      },
      "outputs": [],
      "source": [
        "converter = tf.lite.TFLiteConverter.from_keras_model(model_for_export)\n",
        "pruned_tflite_model = converter.convert()\n",
        "\n",
        "_, pruned_tflite_file = tempfile.mkstemp('.tflite')\n",
        "\n",
        "with open(pruned_tflite_file, 'wb') as f:\n",
        "  f.write(pruned_tflite_model)\n",
        "\n",
        "print('Saved pruned TFLite model to:', pruned_tflite_file)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "c4lv-lRKuMY4"
      },
      "source": [
        "Define a helper function to actually compress the models via gzip and measure the zipped size."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "-E7DXEgUrCDZ"
      },
      "outputs": [],
      "source": [
        "def get_gzipped_model_size(file):\n",
        "  # Returns size of gzipped model, in bytes.\n",
        "  import os\n",
        "  import zipfile\n",
        "\n",
        "  _, zipped_file = tempfile.mkstemp('.zip')\n",
        "  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:\n",
        "    f.write(file)\n",
        "\n",
        "  return os.path.getsize(zipped_file)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "caxUoJ_BunqU"
      },
      "source": [
        "Compare and see that the models are 3x smaller from pruning."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HzSXC_nxuqJX"
      },
      "outputs": [],
      "source": [
        "print(\"Size of gzipped baseline Keras model: %.2f bytes\" % (get_gzipped_model_size(keras_file)))\n",
        "print(\"Size of gzipped pruned Keras model: %.2f bytes\" % (get_gzipped_model_size(pruned_keras_file)))\n",
        "print(\"Size of gzipped pruned TFlite model: %.2f bytes\" % (get_gzipped_model_size(pruned_tflite_file)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z8D7WnFF5DZR"
      },
      "source": [
        "## Create a 10x smaller model from combining pruning and quantization"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "I1c2IecBRCdQ"
      },
      "source": [
        "You can apply post-training quantization to the pruned model for additional benefits."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jy_Lgfh8VkyX"
      },
      "outputs": [],
      "source": [
        "converter = tf.lite.TFLiteConverter.from_keras_model(model_for_export)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "quantized_and_pruned_tflite_model = converter.convert()\n",
        "\n",
        "_, quantized_and_pruned_tflite_file = tempfile.mkstemp('.tflite')\n",
        "\n",
        "with open(quantized_and_pruned_tflite_file, 'wb') as f:\n",
        "  f.write(quantized_and_pruned_tflite_model)\n",
        "\n",
        "print('Saved quantized and pruned TFLite model to:', quantized_and_pruned_tflite_file)\n",
        "\n",
        "print(\"Size of gzipped baseline Keras model: %.2f bytes\" % (get_gzipped_model_size(keras_file)))\n",
        "print(\"Size of gzipped pruned and quantized TFlite model: %.2f bytes\" % (get_gzipped_model_size(quantized_and_pruned_tflite_file)))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BEYsyYVqNgeY"
      },
      "source": [
        "## See persistence of accuracy from TF to TFLite"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "saadXD4JQsBK"
      },
      "source": [
        "Define a helper function to evaluate the TF Lite model on the test dataset."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "b8yBouuGNqls"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "def evaluate_model(interpreter):\n",
        "  input_index = interpreter.get_input_details()[0][\"index\"]\n",
        "  output_index = interpreter.get_output_details()[0][\"index\"]\n",
        "\n",
        "  # Run predictions on ever y image in the \"test\" dataset.\n",
        "  prediction_digits = []\n",
        "  for i, test_image in enumerate(test_images):\n",
        "    if i % 1000 == 0:\n",
        "      print('Evaluated on {n} results so far.'.format(n=i))\n",
        "    # Pre-processing: add batch dimension and convert to float32 to match with\n",
        "    # the model's input data format.\n",
        "    test_image = np.expand_dims(test_image, axis=0).astype(np.float32)\n",
        "    interpreter.set_tensor(input_index, test_image)\n",
        "\n",
        "    # Run inference.\n",
        "    interpreter.invoke()\n",
        "\n",
        "    # Post-processing: remove batch dimension and find the digit with highest\n",
        "    # probability.\n",
        "    output = interpreter.tensor(output_index)\n",
        "    digit = np.argmax(output()[0])\n",
        "    prediction_digits.append(digit)\n",
        "\n",
        "  print('\\n')\n",
        "  # Compare prediction results with ground truth labels to calculate accuracy.\n",
        "  prediction_digits = np.array(prediction_digits)\n",
        "  accuracy = (prediction_digits == test_labels).mean()\n",
        "  return accuracy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TuEFS4CIQvUw"
      },
      "source": [
        "You evaluate the pruned and quantized model and see that the accuracy from TensorFlow persists to the TFLite backend."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VqQTyqz4NsWd"
      },
      "outputs": [],
      "source": [
        "interpreter = tf.lite.Interpreter(model_content=quantized_and_pruned_tflite_model)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "test_accuracy = evaluate_model(interpreter)\n",
        "\n",
        "print('Pruned and quantized TFLite test_accuracy:', test_accuracy)\n",
        "print('Pruned TF test accuracy:', model_for_pruning_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0O5xuci-SonI"
      },
      "source": [
        "## Conclusion"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O2I7xmyMW5QY"
      },
      "source": [
        "In this tutorial, you saw how to create sparse models with the TensorFlow Model Optimization Toolkit API for both TensorFlow and TFLite. You \n",
        "then combined pruning with post-training quantization for additional benefits.\n",
        "\n",
        "You created a 10x smaller model for MNIST, with minimal accuracy difference.\n",
        "\n",
        "We encourage you to try this new capability, which can be particularly important for deployment in resource-constrained environments.\n"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "pruning_with_keras.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
